<template>
  <div class="tourism-container">
      <!-- 左侧导航栏 -->
      <Sidebar />
  
      <!-- 中间部分：景点展示 -->
      <div class="main-content">

        <div class="search-bar-container">
          <!-- 搜索输入框 -->
          <el-input
            v-model="searchQuery"
            placeholder="搜索景点"
            clearable
            @focus="showDropdown = true"
            @blur="handleBlur"
            @input="handleSearchInput"
            @clear="clearSearch"
            class="search-bar-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <!-- 搜索按钮 -->
          <el-button
            icon="Search"
            type="primary"
            class="search-button"
            @click="handleSearchButtonClick"
          >
            搜索
          </el-button>

          <!-- 搜索下拉框 -->
          <div v-if="showDropdown" class="search-dropdown">
            <!-- 搜索历史 -->
            <div class="search-history">
              <h4 class="dropdown-title">搜索历史</h4>
              <ul class="dropdown-list">
                <li
                  v-for="(history, index) in searchHistory"
                  :key="index"
                  @mousedown.prevent="navigateToSpot(history.id)"
                  class="dropdown-item"
                >
                  <el-icon><Clock /></el-icon>
                  {{ history.name }}
                  <el-icon
                    class="delete-icon"
                    @mousedown.prevent="deleteHistory(history.id)"
                  >
                    <Close />
                  </el-icon>
                </li>
              </ul>
            </div>

            <!-- 猜你想搜 -->
            <div class="search-suggestions">
              <h4 class="dropdown-title">猜你想搜</h4>
              <ul class="dropdown-list">
                <li
                  v-for="spot in filteredSpots"
                  :key="spot.id"
                  @mousedown.prevent="navigateToSpot(spot.id)"
                  class="dropdown-item"
                >
                  <el-icon><Location /></el-icon>
                  {{ spot.name }}
                </li>
              </ul>
            </div>
          </div>
        </div>

        <h1 class="title">旅游推荐</h1>
        <div class="card-container">
          <div 
            v-for="spot in spots" 
            :key="spot.id" 
            class="diary-card"
            @click="handleCardClick(spot)"
          >
            <el-image
              :src="spot.images && spot.images.length > 0 ? spot.images[0] : defaultImage"
              class="card-cover"
              fit="cover"
            />
            
            <div class="card-body">
              <h3 class="title">{{ spot.name }}</h3>
              
              <!-- 新增统计信息 -->
              <div class="stats">
                <span class="stat-item">
                  <el-icon><StarFilled /></el-icon>
                  {{ (spot.rating || 0).toFixed(1) }}
                </span>
                <span class="stat-item">
                  <el-icon><Collection /></el-icon>
                  {{ spot.collects || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ (spot.comments || []).length }}
                </span>
              </div>

              <div class="card-actions">
                <el-button 
                  class="action-btn like-btn"
                  :class="{ 'liked': spot.collected }"
                  @click.stop="toggleCollect(spot)"
                >
                  <el-icon><StarFilled /></el-icon>
                  {{ spot.collected ? '已收藏' : '收藏' }}
                </el-button>
                
                <el-button 
                  class="action-btn rewrite-btn"
                  @click.stop="handleWriteDiary(spot)"
                >
                  <el-icon><Edit /></el-icon>
                  写日记
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
  </div>
</template>
  
  <script setup>
  import Sidebar from '@/components/Sidebar.vue' // 引入导航栏组件
  import { ref, computed } from 'vue'
  import { Location, Notebook, Star, StarFilled, Edit, SwitchButton ,Clock,Close} from '@element-plus/icons-vue'
  import { Collection, ChatDotRound } from '@element-plus/icons-vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  // 导入景点数据
  import { attractions } from '@/mock/attractions'
  import { getAttractionsList } from '@/api/attractions'
  import { onMounted } from 'vue'

  
  const router = useRouter()
  const defaultImage = ref('https://via.placeholder.com/300') 
  
  const normalizeSpotData = (spot) => ({
  rating: spot.rating || 0,
  collects: spot.collects || 0,
  comments: spot.comments || [],
  ...spot
})

  const spots = ref(Object.values(attractions).map(normalizeSpotData))
  
  // 获取景点数据的函数需要移动到这里
  const fetchSpots = async () => {
    try {
      const response = await getAttractionsList()
      console.log('API响应数据:', response) // 添加调试日志
      if (response.data.ret === 0) {
        spots.value = response.data.data.data.map(item => ({
          id: item.id,
          name: item.cnName,
          image: item.img_url,
          description: item.description,
          isLiked: false,
          likes: item.num_likes
        }))
        console.log('处理后的数据:', spots.value) // 添加调试日志
      }
    } catch (error) {
      ElMessage.error('获取景点数据失败')
      console.error('获取景点数据失败:', error)
    }
  }
  
  // 确保在组件挂载时获取数据
  onMounted(() => {
    fetchSpots()
  })

  // 点击卡片跳转到 Map 页面
  const handleCardClick = (spot) => {
    router.push({
      name: 'SpotDetail', 
      params: { id: spot.id } // 使用 params 传递 ID
      /* query: { id: spot.id } // 传递景点 ID */
    })
  }
  // 切换喜欢状态
  const toggleCollect = (spot) => {
  spot.collected = !spot.collected
  spot.collects += spot.collected ? 1 : -1
}
  
  // 写日记按钮点击事件
  const handleWriteDiary = (spot) => {
    console.log('撰写日记:', spot.name)
    // 这里可以跳转到写日记页面
    router.push({
    path: '/create-diary',
    query: { title: spot.id}
  })
  }
  
  // 搜索相关状态
  const searchQuery = ref('')
  const searchHistory = ref([])
  const showDropdown = ref(false)

  // 过滤后的景点列表
  const filteredSpots = computed(() => {
    if (!searchQuery.value) return []
    return spots.value.filter((spot) =>
      spot.name.includes(searchQuery.value)
    )
  })

  // 搜索输入处理
  const handleSearchInput = () => {
    // 可以在这里添加额外的逻辑，例如调用后端接口获取推荐结果
  }

  // 清空搜索
  const clearSearch = () => {
    searchQuery.value = ''
  }

  // 点击搜索按钮处理
  const handleSearchButtonClick = () => {
    if (searchQuery.value) {
      const matchedSpot = spots.value.find((spot) =>
        spot.name.includes(searchQuery.value)
      )
      if (matchedSpot) {
        navigateToSpot(matchedSpot.id)
      } else {
        alert('未找到匹配的景点')
      }
    }
  }

  // 跳转到景点详情页面
  const navigateToSpot = (id) => {
    // 添加到搜索历史
    const spot = spots.value.find((s) => s.id === id)
    if (spot && !searchHistory.value.some((h) => h.id === id)) {
      searchHistory.value.unshift(spot)
    }

    // 跳转到 SpotDetail 页面
    router.push({
      name: 'SpotDetail',
      params: { id },
    })

    // 隐藏下拉框
    showDropdown.value = false
  }

  // 清除搜索历史
  const deleteHistory = (id) => {
    searchHistory.value = searchHistory.value.filter((h) => h.id !== id)
  }

  // 处理失去焦点时隐藏下拉框
  const handleBlur = () => {
    setTimeout(() => {
      showDropdown.value = false
    }, 200) // 延迟隐藏以确保点击事件触发
  }
  </script>
  
<style scoped lang="scss">
  // 添加多行文本省略 mixin
  @mixin text-ellipsis($lines) {
    display: -webkit-box;
    -webkit-line-clamp: $lines;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .tourism-container {
    display: flex;
    height: 100vh;
    width: 100%; /* 确保容器占满页面宽度 */
  }
  
  .main-content {
    flex: 1;
    padding: 20px;
    background-color: #fff;
    margin-left: 20%; /* 避免内容被导航栏遮挡 */
    display: flex;
    flex-direction: column; /* 改为列布局 */
    align-items: center; /* 水平居中 */
    width: calc(100% - 16.666%); /* 确保内容宽度占满剩余空间 */
  }
  
  .title {
    margin-bottom: 20px; /* 调整标题与内容的间距 */
   /* align-items: center;*/
    font-size: 30px;
    margin-bottom: 30px;
  }
  
  .card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  width: 100%;
  padding: 0 2rem;
}

.diary-card {
  background: white;
  border-radius: 0.75rem;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  transition: transform 0.3s ease;
  position: relative;
  padding-bottom: 60px;

  &:hover {
    transform: translateY(-4px);
  }
}

.card-cover {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.card-body {
  padding: 1rem;

  .title {
    font-size: 1.3rem;  /* 调大标题字号 */
    margin: 0 0 1rem 0;
    line-height: 1.4;
    @include text-ellipsis(2);
  }
}

.card-actions {
  position: absolute;
  right: 1rem;
  bottom: 1rem;
  display: flex;
  gap: 0.5rem;
  z-index: 2;

  /* 复用日记页面的按钮样式 */
  .action-btn {
    transition: all 0.3s ease;
    border-radius: 20px;
    padding: 8px 16px;
    font-size: 0.85rem;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
  }
  
  .like-btn {
    background: rgba(255,255,255,0.9);
    border: 1px solid #ff4d4f;
    color: #ff4d4f;
    
    &.liked {
      background: #ff4d4f;
      color: white;
    }
  }
  
  .rewrite-btn {
    background: rgba(255,255,255,0.9);
    border: 1px solid #52c41a;
    color: #52c41a;
  }
}



    /* 搜索栏容器 */
  .search-bar-container {
    position: relative;
    max-width: 600px; /* 搜索栏宽度 */
    margin: 0 auto;
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 25px; /* 圆角 */
    padding: 5px 15px; /* 内边距 */
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  }

  /* 搜索输入框 */
  .search-bar-input {
    flex: 1;
    border: none;
    outline: none;
    background: transparent;
    font-size: 16px;
    padding: 10px;
    color: #333;
  }

  /* 搜索按钮图标 */
  .search-button {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 15px;
    color: #999;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: color 0.3s;
  }

  .search-button:hover {
    color: #333;
  }

  /* 搜索下拉框 */
  .search-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 10;
    padding: 15px;
    margin-top: 10px; /* 与搜索栏的间距 */
  }

  /* 下拉框标题 */
  .dropdown-title {
    font-size: 14px;
    margin-bottom: 10px;
    color: #999;
    font-weight: bold;
  }

  /* 搜索历史和猜你想搜的列表 */
  .dropdown-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-wrap: wrap; /* 支持多行显示 */
    gap: 10px; /* 项目之间的间距 */
  }

  /* 搜索历史的标签样式 */
  .dropdown-item {
    background: #f5f5f5;
    border-radius: 15px;
    padding: 5px 15px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: background 0.3s;
  }

  .dropdown-item:hover {
    background: #e0e0e0;
  }

  /* 删除图标 */
  .delete-icon {
    color: #999;
    cursor: pointer;
    margin-left: 10px;
  }

  .delete-icon:hover {
    color: #ff4d4f;
  }

  /* 新增统计样式 */
  .stats {
    display: flex;
    gap: 1.5rem;
    color: #666;
    font-size: 0.95rem;
    margin: 1rem 0;

    .stat-item {
      display: flex;
      align-items: center;
      gap: 0.3rem;

      .el-icon {
        color: var(--el-color-primary);
        font-size: 1.1rem;
      }
    }
  }

  /* 调整标题间距 */
  .card-body .title {
    margin-bottom: 0.5rem;
  }
  /* 新增文本省略mixin */
@mixin text-ellipsis($lines) {
  display: -webkit-box;
  -webkit-line-clamp: $lines;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
